/*
 * File Name : users.cpp
 * Auther : dream.liuguobiao
 * Create Date : 2010-5-11
 * Last Edit : 2010-5-14
 */

#include "users.h"

users *users::instance_users = (users*)NULL ;

users::users()
:first_user(NULL),last_user(NULL),new_ID(500),user_count(0)
{
}

users *users::get_users(){
  if( 0 == instance_users ){
    instance_users = new users();
  }
  return instance_users;
}

user *users::find_user_by_name( std::string *name){
  user *tmp_user ;
  for( tmp_user = first_user ; NULL != tmp_user ; tmp_user = tmp_user->get_next_user() ){
    if( *name == *(tmp_user->get_name() ) )return tmp_user;
  }
  return NULL;
}

user *users::find_user_by_ID( int ID){
  user *tmp_user ;
  for( tmp_user = first_user ; NULL != tmp_user ; tmp_user = tmp_user->get_next_user() ){
    if( ID == tmp_user->get_ID() )return tmp_user;
  }
  return NULL;
}

bool users::insert_user(user *new_user){
  user *tmp_user;
  std::string name = *(new_user->get_name() );
  new_user->set_ID( new_ID ++);
  for( tmp_user = first_user ; NULL != tmp_user ; tmp_user = tmp_user->get_next_user() ){
    if( name == *(tmp_user->get_name() ) )return 1;
  }
  if( NULL == last_user ){
    first_user = last_user = new_user;
  }else {
    last_user->set_next_user( new_user );
    last_user = new_user;
  }
  user_count ++;
return 0;
}

bool users::delete_user_by_name( std::string *name ){
  user *tmp_user ;
  user *previouse_user ;
  for( tmp_user = first_user ; NULL != tmp_user ; tmp_user = tmp_user->get_next_user() ){
    if( *name == *(tmp_user->get_name() ) ){
      previouse_user->set_next_user( tmp_user->get_next_user() );
      if( last_user == tmp_user )
        last_user = previouse_user;
      delete tmp_user;
      user_count -- ;
      return 0;
    }
    previouse_user = tmp_user;
  }
  return 1;
}

int users::get_user_count(){
  return user_count;
}
